﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

namespace FlashSolution
{
    public class FlashVarsEditorPart : EditorPart
    {
        private System.Web.UI.WebControls.TextBox textbox = null;

        public FlashVarsEditorPart()
        {
            ID = "FlashVarsEditorPart";
        }

        protected override void CreateChildControls()
        {
            this.Title = "FlashVars";

            textbox = new TextBox();
            textbox.TextMode = TextBoxMode.MultiLine;
            textbox.Rows = 6;

            this.Controls.Add(textbox);
        }

        private Dictionary<string, string> GetTextboxText()
        {
            Dictionary<string, string> flashvars = new Dictionary<string, string>();
            
            StringReader sr = new StringReader(textbox.Text);
            string line = sr.ReadLine();
            while (line !=null)
            {
                string[] ss = line.Split(new char[] { '=' }, 2);

                if (ss.Length==2)
                {
                    string parameter = ss[0].Trim();
                    string value = ss[1].Trim();
                    flashvars.Add(parameter, value);
                }
                line = sr.ReadLine();
            }
            return flashvars;
        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            FlashWebPart flashwebpart = this.WebPartToEdit as FlashWebPart;
            if (flashwebpart != null && textbox != null)
            {
                flashwebpart.FlashAttributes.flashvars = GetTextboxText();
            }
            return true;
        }

        public override void SyncChanges()
        {
            EnsureChildControls();
            FlashWebPart flashwebpart = this.WebPartToEdit as FlashWebPart;
            if (flashwebpart != null && textbox != null )
            {
                System.Text.StringBuilder flashvars = new System.Text.StringBuilder();
                foreach (KeyValuePair<string,string> flashvar in flashwebpart.FlashAttributes.flashvars)
                {
                    flashvars.AppendLine(flashvar.Key + "=" + flashvar.Value);
                }
                textbox.Text = flashvars.ToString();
            }
            
        }

    }
}
